package com.gpnu7_412.yanzhi.interceptors;

import com.gpnu7_412.yanzhi.util.JwtUtils;
import com.gpnu7_412.yanzhi.util.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

/**
 * 登录验证拦截器
 * @author ZZH
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        // CROS 复杂请求时会首先发送一个 OPTIONS 请求做嗅探，来测试服务器是否支持本次请求，请求成功后才会发送真实的请求；
        // 而 OPTIONS 请求不会携带数据，导致这个请求被拦截了，直接返回了状态码，响应头中没携带解决跨域问题的头部信息，出现了跨域问题。
        // https://cloud.tencent.com/developer/article/1768352
        if("OPTIONS".equals(request.getMethod().toUpperCase())) {
            return true;
        }

        // 获取 Jwt 令牌
        String jwtToken = request.getHeader("Authorization");

        // 验证 Jwt 令牌
        try {
            // 尝试从 Redis 中获取相同的 Jwt 令牌
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            String redisToken = operations.get(jwtToken);
            if (redisToken == null) {
                // Jwt 令牌已过期
                throw new RuntimeException("Jwt 令牌已过期");
            }
            Map<String, Object> claims = JwtUtils.parseJwtToken(jwtToken);
            ThreadLocalUtil.set(claims);
        } catch (Exception e) {
            response.setStatus(401);
            ThreadLocalUtil.remove();
            return false;
        }
        return true;
    }
}
